<?php
session_start();

error_reporting(E_ALL);
//ob_start();

require_once('classes/libs/ExtDirect/API.php');
require_once('classes/libs/ExtDirect/Router.php');
require_once('classes/services.common.php');

$log = Logger::getRootLogger();

//$log->debug('Dispaching request...');
// this should alwasy be set but if its not, then execute api.php without outputting it
if(!isset($_SESSION['ext-direct-state'])) {
    ob_start();
    include('api.php');
    ob_end_clean();
}

$api = new ExtDirect_API();
$api->setState($_SESSION['ext-direct-state']);

//$log->debug('-------------REQUEST DISPACHING----------------');
//$log->debug('Request HTTP_RAW_POST_DATA: ' . $GLOBALS['HTTP_RAW_POST_DATA'] );
//$log->debug('Request POST Action: ' .  $_POST['extAction'] . "->" . $_POST['extMethod'] . " tid:" . $_POST['extTID'] );
//$log->debug('Request POST Action: ' .  print_r($_POST,true) );

if(ACL_LEARNING_MODE) {
	$parsed_api = $api->getParsedAPI();
	foreach ($parsed_api['actions'] as $action_name => $action){
		if($acl->createResource( $action_name )){
			foreach ( $action as $method ){
				$acl->createAction( $action_name, $method['name']);
				$log->debug('Learning mode creating:' . $action_name . "->" . $method['name']  );
			}
		}
	}
}



//antes del dispache verificar que tenga acceso a todos los permisos

//suponiendo que no tiene permisos
/*
//puede salir del POST como del  HTTP_RAW_POST_DATA. Igual pensar en modificar el Router.php Para pasarle un ACL Manager y que haga lo solicitado.
$response = array(  'type' => 'rpc',
                    'tid' => $_POST['extTID'],
                    'action' => $_POST['extAction'],
                    'method' => $_POST['extMethod'],
					'result'=>array('success'=>false,'message'=>'Error, No tiene privilegios para la operacion solicitada.')
                );
echo(json_encode($response));
die();
/**/

$router = new ExtDirect_Router($api);
$router->dispatch();
$response = $router->getResponse(false); // true to print the response instantly

//para la seguridad hay que parsear o el HTTP_RAW_POST_DATA o el POST

//$log->debug('Request response:' . $response );
//ob_end_clean();
echo($response);/**/
